class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int count = 0;
        int mid = 0;
        // 二分查找
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                count++;
                break;
            }
        }
        // 向左延伸
        int k = mid - 1;
        while (k >= 0) {
            if (nums[k] == target) {
                k--;
                count++;
            } else {
                break;
            }
        }
        // 向右延伸
        k = mid + 1;
        while (k < nums.length) {
            if (nums[k] == target) {
                k++;
                count++;
            } else {
                break;
            }
        }
        return count;
    }
}